package org.canx.service;

import org.apache.log4j.Logger;
import org.canx.dao.GTokenMapper;
import org.canx.model.GToken;
import org.canx.utils.ConstantCommon;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.*;

/**
 * Created by weican on 2017/7/27.
 */
@Service
public class TokenService {
    private static Logger logger = Logger.getLogger(TokenService.class);

    @Autowired
    private GTokenMapper tokenMapper;


    /**
     * 创建token
     *
     * @param userName 用户名
     * @return 成功返回token，失败返回null
     */
    public String createNewToken(String userName) {
        GToken token = new GToken();
        token.setUserName(userName);
        token.setToken(UUID.randomUUID().toString());
        token.setExpiredTime(getExpiredTime(ConstantCommon.TOKEN_EXPIRED_HOUR));
        tokenMapper.insertSelective(token);

        logger.info("token == " + token.getToken());

        return token.getId() != null ? token.getToken() : null;
    }

    /**
     * 延长token失效时间
     *
     * @param token
     */
    public void extendExpiredTime(String token) {
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("expiredTime", getExpiredTime(ConstantCommon.TOKEN_EXPIRED_HOUR));
        tokenMapper.updateExpiredTime(map);
    }

    /**
     * token有效性校验
     * 0 token不存在，1 token失效，2 token即将过期 ， 3 token正常
     */
    public int checkTokenIsExist(String token) {
        GToken t = tokenMapper.findByToken(token);
        if (t == null) {
            return 0;
        }

        if ((new Date().getTime()) > t.getExpiredTime().getTime()) {
            return 1;
        } else if (t.getExpiredTime().getTime() >= getExpiredTime(-ConstantCommon.SOON_EXPIRED_HOUR).getTime()
                && t.getExpiredTime().getTime() <= getExpiredTime(ConstantCommon.SOON_EXPIRED_HOUR).getTime()) {
            extendExpiredTime(token);
            return 2;
        } else {
            return 3;
        }
    }


    /**
     * 获取失效时间
     *
     * @param date 时间
     * @param hour 小时
     * @return
     */
    public static Timestamp getExpiredTime(Date date, int hour) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.HOUR_OF_DAY, hour);
        date = cal.getTime();
        return new Timestamp(date.getTime());
    }

    public static Timestamp getExpiredTime(int hour) {
        return getExpiredTime(new Date(), hour);
    }
}
